# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

require 'json'


default_platform(:ios)

def upload_bugly_symbols(bundle_id:, version:, build_no:, output_dir:, output_name:)
  jar_path = "buglyqq-upload-symbol.jar"

  dsym_zip_path = "#{output_dir}/#{output_name}.app.dSYM.zip"
  sh("unzip -o #{dsym_zip_path} -d #{output_dir}/dysm")

  # 解压后 dSYM 路径
  matched_dsym = "#{output_dir}/dysm/Runner.app.dSYM"

  unless File.directory?(matched_dsym)
    UI.error("❌ dSYM 路径无效: #{matched_dsym}")
    return
  end

  command = [
    "java -jar #{jar_path}",
    "-appid 39e12b979f",
    "-appkey 21bd4417-4037-43fc-8d11-69fff7676bb8",
    "-bundleid #{bundle_id}",
    "-version #{version}",
    "-buildNo #{build_no}",
    "-platform IOS",
    "-inputSymbol #{matched_dsym}"
  ].join(" ")

  UI.message("🚀 开始上传符号表至 Bugly")
  sh(command)
end


def updateProjectBuildNumber


  plist_path = File.expand_path("../Runner.xcodeproj", __dir__)
  version = get_version_number(
    xcodeproj: plist_path
  )


  json_text = File.read("config.txt")               
  config = JSON.parse(json_text)                  

  build = config["build"]
  nextBuild = build.to_i + 1

  ENV["BT_VERSION"] = version
  ENV["BT_BUILD"] = build
  ENV["BT_NEXT_BUILD"] = nextBuild.to_s

  xcBuild = get_build_number()
  ENV["xcBuild"] = xcBuild

  increment_build_number(
    build_number: ENV["BT_NEXT_BUILD"],
  )

  puts("version #{version};build #{build};nextBuild #{nextBuild};xcBuild #{xcBuild};btConfig #{config}")

end 

def resetProjectBuildNumber

  increment_build_number(
    build_number: ENV["xcBuild"],
  )

  build = ENV["BT_NEXT_BUILD"]

  json_hash = {
    build: build
  }

  File.write("config.txt", JSON.generate(json_hash))

end


def current_path(suffix = "")
  date = Time.now.strftime("%Y-%m-%d_%H-%M-%S")
  desktop_path = File.expand_path("~/Desktop")
  folder_name = "ipa/famece"

  # 如果传入了 suffix，则拼接在 folder_name 之后
  folder_name = "#{folder_name}/#{suffix}" unless suffix.empty?

  output_directory = "#{desktop_path}/#{folder_name}/#{date}_#{ENV["BT_VERSION"]}_#{ENV["BT_NEXT_BUILD"]}"
  FileUtils.mkdir_p(output_directory)
  output_directory
end

platform :ios do
  desc "Description of what the lane does"
lane :bt_adhoc do
  updateProjectBuildNumber
  output_dir = current_path("ad-hoc")
  output_name = "afterwork_adhoc"
  bundle_id = "com.ty.afterwork"
  build_ios_app(
    scheme: "btmodulePro",
    clean:false,
    output_name:output_name,
    output_directory: output_dir,
    export_options: {
      method: "ad-hoc",
      provisioningProfiles: { 
        bundle_id => "after_work_adhoc_profile",
      }
    }
  )
  #commit = last_git_commit
  #message = commit[:message]
  #fir_cli api_token: "79f12812ce966f0216af0245832786d4",  changelog: message
  #sh("python3 build_success_email.py") # Example
  resetProjectBuildNumber
  end

lane :bt_adhoc_cq do
  updateProjectBuildNumber
  output_dir = current_path("ad-hoc")
  output_name = "faceme_cq_adhoc"
  bundle_id = "com.chuanqing.app"
  build_ios_app(
    scheme: "Runner",
    clean:false,
    output_name:output_name,
    output_directory: output_dir,
    export_options: {
      method: "ad-hoc",
      provisioningProfiles: { 
        bundle_id => "chuanqing_adhoc",
      }
    }
  )
  #commit = last_git_commit
  #message = commit[:message]
  #fir_cli api_token: "79f12812ce966f0216af0245832786d4",  changelog: message
  #sh("python3 build_success_email.py") # Example
  resetProjectBuildNumber
  end

lane :bt_dis do
  updateProjectBuildNumber
  output_dir = current_path("dis")
  output_name = "faceme_dis"
  bundle_id = "com.ty.faceme"
  build_ios_app(
    scheme: "RunnerPro",
    clean:false,
    output_name:output_name,
    output_directory: output_dir,
    export_options: {
      method: "app-store",
      "compileBitcode"=>false,
      "uploadBitcode"=>false,
      "uploadSymbols"=>false,
      provisioningProfiles: {
        bundle_id => "faceme_appstore_profile",
      }
    }
  )
  
  # 上传 Bugly 符号表
#   upload_bugly_symbols(
#     bundle_id: bundle_id,
#     version: ENV["BT_VERSION"],
#     build_no: ENV["BT_NEXT_BUILD"],
#     output_dir: output_dir,
#     output_name: output_name,
#   )
  resetProjectBuildNumber
  end

lane :test do
  sh("unzip -o /Users/mini2021/Desktop/ipa/afterwork/dis/2025-06-10_15-50-23(1.3.5-175)/afterwork_dis.app.dSYM.zip -d /Users/mini2021/Desktop/ipa/afterwork/dis/2025-06-10_15-50-23(1.3.5-175)/")
end


after_all do |lane|
  #say("Successfully finished deployment (#{lane})!")
  notification(title: "执行#{lane}成功!", message: "执行#{lane}成功!")
end


error do |lane, exception|
  puts("#{exception.message}")
  notification(title: "执行#{lane}发生异常!", message: "发生异常, 详情请查看控制台!")
  resetProjectBuildNumber
  end

end
